# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals


class GithubLoginSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class GithubLoginDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # 功能：处理请求，对于通过中间件的每个请求都调用此方法
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request #继续处理请求
        # - or return a Response object # 不会调用其他中间件的process_request方法
        # - or return a Request object # 直接返回到引擎，不会再给其他中间件进行处理
        # - or raise IgnoreRequest: process_exception() methods of  # 抛出IgnoreRequest异常给process_exception来处理
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # 功能：处理响应，对于通过中间件的每个响应都调用此方法
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object  # 继续调用其他中间件的process_response
        # - return a Request object  # 停止中间件的调用返回给引擎，交给调度器进行排队
        # - or raise IgnoreRequest  # 抛出IgnoreRequest异常给process_exception来处理
        return response

    def process_exception(self, request, exception, spider):
        # 处理请求时发生了异常时调用
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception  # 无异常，继续调用其他中间件的process_exception
        # - return a Response object: stops process_exception() chain  # 返回给process_response 停止调用其他的中间件的process_exception
        # - return a Request object: stops process_exception() chain #  返回给引擎，交个调度器，停止调用其他中间件的process_exception，
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


from .settings import user_agent_list
import random


class MiddleUADownloaderMiddleware(object):
    def process_request(self, request, spider):
        # 使用UA池进行UA伪装
        request.headers['User-Agent'] = random.choice(user_agent_list)
        return None


from scrapy import signals
from .settings import IPPOOL


class MyproxiesDownloaderMiddleware(object):
    def __init__(self, ip=''):
        self.ip = ip

    def process_request(self, request, spider):
        thisip = random.choice(IPPOOL)
        # 要在meta里设置proxy
        request.meta['proxy'] = 'http://' + thisip['ipaddr']

    def process_response(self, request, response, spider):
        return response

    def process_exception(self, request, exception, spider):
        pass
